<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :sm="12" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name" :rules="[{ required: true, message: '班组名称为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="班组名称" tooltip="考勤班组的显示名称，用于区分不同的班组" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" disabled class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :lg="12" class="mb20">
							<el-form-item ref="Entity_Order_FormItem" prop="Entity.Order">
								<template #label>
									<WtmLabelTooltip label="排序" tooltip="班组规则的排序，数值越小越靠前" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.Order" disabled class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_Description_FormItem" prop="Entity.Description">
								<template #label>
									<WtmLabelTooltip label="班组描述" tooltip="班组的详细描述信息，说明班组的用途和特点" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Description" type="textarea" :rows="3" disabled class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>排班设置</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item
								ref="Entity_Type_FormItem"
								prop="Entity.Type"
								:rules="[{ required: true, message: '排班类型为必填项', trigger: 'change' }]"
							>
								<template #label>
									<WtmLabelTooltip label="排班类型" tooltip="班组的排班模式（行政班/三班倒/两班倒）" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.Type" disabled class="width100">
									<el-option v-for="item in SHIFT_TYPES" :key="item.key" :label="item.label" :value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>

						<!-- 排班模式配置 -->
						<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.vmModel.Entity.Type">
							<el-form-item
								:prop="stateData.vmModel.Entity.Type === '行政班' ? 'WorkDays' : 'WorkDate'"
								:rules="[
									{ required: true, message: stateData.vmModel.Entity.Type === '行政班' ? '请选择工作日' : '请选择工作日期', trigger: 'change' },
								]"
							>
								<template #label>
									<WtmLabelTooltip label="排班模式" tooltip="排班模式配置：行政班存储工作日，班倒模式存储班次模板" />
								</template>

								<!-- 行政班：多选工作日 -->
								<el-checkbox-group
									v-if="stateData.vmModel.Entity.Type === '行政班'"
									v-model="stateData.vmModel.WorkDays"
									multiple
									clearable
									collapse-tags
									collapse-tags-tooltip
									placeholder="请选择工作日"
									border
									disabled
								>
									<el-checkbox v-for="item in stateData.shiftItems" :key="item.Value" :label="item.Text" :value="item.Value"></el-checkbox>
								</el-checkbox-group>

								<!-- 班倒模式：选择工作日期和班次标签 -->
								<template v-else>
									<div class="space-y-3">
										<el-date-picker
											v-model="stateData.vmModel.WorkDate"
											type="date"
											placeholder="请选择工作日期"
											format="YYYY-MM-DD"
											value-format="YYYY-MM-DD"
											disabled
											class="width100 mb-3"
										></el-date-picker>
									</div>
									<el-form-item prop="ShiftTag">
										<template #label>
											<WtmLabelTooltip label="班次标签" tooltip="班倒模式的班次标签" />
										</template>
										<el-radio-group v-model="stateData.vmModel.ShiftTag" disabled>
											<el-radio v-for="item in stateData.shiftItems" :key="item.Value" :label="item.Value" :value="item.Value">
												{{ item.Text }}
											</el-radio>
										</el-radio-group>
									</el-form-item>
								</template>
							</el-form-item>

							<!-- 排班预览 -->
							<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.vmModel.Entity.Type && stateData.vmModel.Entity.Type !== '行政班'">
								<SchedulePreview
									:shift-type="stateData.vmModel.Entity.Type"
									:work-date="stateData.vmModel.WorkDate"
									:shift-tag="stateData.vmModel.ShiftTag"
									:shift-sequence="stateData.allShiftItems?.[stateData.vmModel.Entity.Type] || []"
									:auto-calculate="true"
									title="排班预览"
									:show-type-selector="false"
									:show-date-selector="false"
									:readonly="true"
								/>
							</el-col>
						</el-col>

						<!-- 未选择类型时显示提示 -->
						<el-col :xs="24" :lg="24" class="mb20" v-else>
							<el-form-item>
								<template #label>
									<WtmLabelTooltip label="排班模式" tooltip="排班模式配置：行政班存储工作日，班倒模式存储班次模板" />
								</template>
								<el-alert title="请先选择排班类型" type="info" :closable="false" show-icon></el-alert>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>班次管理</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="SelectedShiftsIds_FormItem" prop="SelectedShiftsIds">
								<template #label>
									<WtmLabelTooltip label="班次列表" tooltip="该班组下包含的所有考勤班次" />
								</template>
								<el-select
									v-model="stateData.vmModel.SelectedShiftsIds"
									multiple
									filterable
									clearable
									collapse-tags
									collapse-tags-tooltip
									:max-collapse-tags="4"
									placeholder="请选择班次"
									class="width100"
									disabled
								>
									<el-option v-for="item in stateData.AllSysAttendanceShifts" :key="item.Value" :label="item.Text" :value="item.Value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>

						<!-- 班次标签映射显示区域（只读） -->
						<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.vmModel.SelectedShiftsIds && stateData.vmModel.SelectedShiftsIds.length > 0">
							<el-form-item>
								<template #label>
									<WtmLabelTooltip label="班次标签设置" tooltip="每个班次对应的标签" />
								</template>
								<div class="shift-tag-mapping">
									<div v-for="shift in selectedShiftsWithNames" :key="shift.value" class="shift-tag-item">
										<div class="shift-name">{{ shift.text }}</div>
										<el-select
											v-model="stateData.vmModel.ShiftTagMapping[shift.value]"
											placeholder="未设置"
											class="tag-selector"
											disabled
										>
											<el-option v-for="tag in shiftTagOptions" :key="tag.value" :label="tag.label" :value="tag.value"></el-option>
										</el-select>
									</div>
								</div>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-time"></i>
						<span>工时折算</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :sm="12" :lg="12" class="mb20">
							<el-form-item ref="Entity_StandardWorkMinutes_FormItem" prop="Entity.StandardWorkMinutes">
								<template #label>
									<WtmLabelTooltip label="标准工作时长" tooltip="班组标准工作时长，单位为分钟" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.StandardWorkMinutes" disabled class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :lg="12" class="mb20">
							<el-form-item ref="Entity_AttendanceDays_FormItem" prop="Entity.AttendanceDays">
								<template #label>
									<WtmLabelTooltip label="折算出勤天数" tooltip="根据标准工作时长折算的考勤天数" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.AttendanceDays" disabled class="width100" :precision="2"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.details;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysAttendanceShiftGroupApi as api } from '/@/views/hr/sysattendanceshiftgroup/api';
import other from '/@/utils/other';
import { ISysAttendanceShiftGroupVm } from '/@/views/hr/sysattendanceshiftgroup/api/interface';
import { IViewModel } from '/@/types/common';
import SchedulePreview from '/@/components/schedulePreview/index.vue';
// 排班类型选项
const SHIFT_TYPES = [
	{ key: '行政班', value: '行政班', label: '行政班' },
	{ key: '三班倒', value: '三班倒', label: '三班倒' },
	{ key: '两班倒', value: '两班倒', label: '两班倒' },
	{ key: '上一休二', value: '上一休二', label: '上一休二' },
];

// 班次标签选项
const shiftTagOptions = [
	{ value: 'A', label: 'A', color: '#67c23a' },
	{ value: 'B', label: 'B', color: '#409eff' },
	{ value: 'C', label: 'C', color: '#e6a23c' },
];

// 按钮文本常量
const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const stateData = reactive<IViewModel<ISysAttendanceShiftGroupVm>>({
	vmModel: {
		Entity: {
			Name: null,
			Description: null,
			Type: null,
			SchedulePattern: null,
			Shifts: null,
			Order: null,
			AttendanceDays: null,
			StandardWorkMinutes: null,
		},
		ActionName: null,
		IsMyApprove: null,
		SelectedShiftsIds: [],
		ShiftTagMapping: {},
		WorkDays: [],
		WorkDate: null,
		ShiftTag: null,
	},
	SimpleSchedule: {} as { [key: string]: string }, // 排班预览数据，键为日期，值为班次类型
	AllSysAttendanceShifts: [],
	shiftItems: [],
	allShiftItems: [],
});

// 取消
const onClose = () => {
	closeDialog();
};

// 简化数据处理函数
const processApiResponse = (response: any, defaultValue: any = []) => {
	return response?.status === 'fulfilled' ? response.value : defaultValue;
};

// 计算属性：获取选中班次的详细信息
const selectedShiftsWithNames = computed(() => {
	if (!stateData.vmModel.SelectedShiftsIds || stateData.vmModel.SelectedShiftsIds.length === 0) {
		return [];
	}

	return stateData.vmModel.SelectedShiftsIds.map((shiftId) => {
		const shift = stateData.AllSysAttendanceShifts.find((item: any) => item.Value === shiftId);
		return {
			value: shiftId,
			text: shift ? shift.Text : shiftId,
		};
	});
});

// 简化班次数据过滤
const filterShiftItemsByType = (type: string) => {
	const rawItems = stateData.allShiftItems?.[type] || [];
	stateData.shiftItems = rawItems.map((item: any) => (typeof item === 'string' ? { Text: item, Value: item } : item));
};

// 加载选择列表数据
const loadData = async () => {
	try {
		const [shiftResponse, shiftsListResponse, entityResponse] = await Promise.allSettled([
			api().getShiftItems(),
			other.getSelectList('/api/SysAttendanceShiftGroup/GetSysAttendanceShifts', [], false),
			api().get(stateData.vmModel.Entity.ID ?? ''),
		]);

		// 处理所有数据
		stateData.allShiftItems = processApiResponse(shiftResponse, []);
		stateData.AllSysAttendanceShifts = processApiResponse(shiftsListResponse, []);

		// 加载实体数据
		const entityData = processApiResponse(entityResponse, null);
		if (entityData) {
			other.setValue(stateData.vmModel, entityData);
			
			// 回显ShiftTagMapping数据
			if (entityData.ShiftTagMapping) {
				stateData.vmModel.ShiftTagMapping = entityData.ShiftTagMapping;
			}
			
			// 直接使用接口返回的SimpleSchedule数据
			if (entityData?.SimpleSchedule) {
				stateData.SimpleSchedule = entityData.SimpleSchedule;
			}
		}

		// 如果有排班类型，过滤对应的班次
		if (stateData.vmModel.Entity.Type) {
			filterShiftItemsByType(stateData.vmModel.Entity.Type);
		}
	} catch (error) {
		console.error('加载数据失败:', error);
		stateData.AllSysAttendanceShifts = [];
	}
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>

<style scoped>
.space-y-3 > * + * {
	margin-top: 12px;
}

.mb-3 {
	margin-bottom: 12px;
}

.mb20 {
	margin-bottom: 20px;
}

.form-section {
	margin-bottom: 32px;
	padding-bottom: 24px;
	border-bottom: 1px solid #ebeef5;
}

.form-section:last-child {
	border-bottom: none;
	margin-bottom: 0;
	padding-bottom: 0;
}

.section-title {
	display: flex;
	align-items: center;
	gap: 8px;
	margin-bottom: 20px;
	font-weight: 600;
	font-size: 16px;
	color: #303133;
}

.section-title i {
	color: #409eff;
	font-size: 18px;
}

.width100 {
	width: 100%;
}

/* 紧凑简约的班次标签映射样式 - 占满屏幕宽度 */
.shift-tag-mapping {
	border: 1px solid #dcdfe6;
	border-radius: 4px;
	background-color: #fafafa;
	padding: 16px;
	display: flex;
	flex-direction: column;
	gap: 12px;
	width: 100%;
}

.shift-tag-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12px 16px;
	background-color: #ffffff;
	border: 1px solid #e4e7ed;
	border-radius: 4px;
	width: 100%;
}

.shift-name {
	color: #606266;
	flex: 1;
	margin-right: 16px;
	font-size: 14px;
}

.tag-selector {
	width: 120px;
	flex-shrink: 0;
}
</style>
